/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * storage工具类
 */
import featureAbility from '@ohos.ability.featureAbility'
import dataStorage from '@ohos.data.storage'
import CommonLog from './CommonLog';

const TAG = 'StorageUtils'
export default class StorageUtils {
	private static localDirPath: string = ""
	private static storage
	private static async save(key,value) {
		try{
			CommonLog.info(TAG,`save:key = ${key},value = ${value}`)
			let storage = await this.getStorage()
			storage.putSync(key, value.toString())
			storage.flushSync()
			CommonLog.info(TAG,`save success:key = ${key},value = ${value}`)
		}catch(err){
			CommonLog.error(TAG,`save fail key=${key},value=${value},error=${err}`)
		}
	}

	private static async getValue(key,defValue):Promise<any>{
		try {
			CommonLog.info(TAG,`getValue key:${key},defValue:${defValue}` )
			let storage = await this.getStorage()
			let value = storage.getSync(key,defValue)
			CommonLog.info(TAG,`getValue key:${key},defValue:${defValue},value:${value}` )
			return value
		} catch (error) {
			CommonLog.info(TAG,`getValue fail key:${key},defValue:${defValue},error:${error}` )
			return defValue
		}
	}

	private static async getStorage(){
		if (!this.storage) {
			CommonLog.info(TAG,`getStorage getStorageSync start` )
			let context = featureAbility.getContext()
			CommonLog.info(TAG,`getStorage getContext success` )
			let localDirPath = await context.getOrCreateLocalDir()
			this.storage = dataStorage.getStorageSync(localDirPath + '/files/parkingSystem')
			CommonLog.info(TAG,`getStorage getStorageSync success` )
		}
		CommonLog.info(TAG,`getStorageSync return ${this.storage}` )
		return this.storage
	}

	public static async getModel(){
		return this.getValue('modelList', JSON.stringify([]))
	}

	public static async setModel(data){
		return this.save('modelList', JSON.stringify(data))
	}

	public static async clearModel(){
		return this.save('modelList', JSON.stringify([]))
	}
}